package com.example.lcode.binary;

/**
 * 编写一个高效的算法来判断 m x n 矩阵中，是否存在一个目标值。该矩阵具有如下特性：
 *
 * 每行中的整数从左到右按升序排列。
 * 每行的第一个整数大于前一行的最后一个整数。
 *
 * 输入：matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
 * 输出：true
 *
 * @version 1.0
 * @author: ChuJie_Lin
 * @since: 2021-11-09 10:12
 **/
public class Question74 {

    public boolean searchMatrix(int[][] matrix, int target) {
         // 纵向二分查找
        int yIndex = searchTargetYIndex(matrix, 0, matrix.length - 1, target);
        if (yIndex == -1) {
            return false;
        }
        // 横向二分查找
        int xIndex = searchTargetXIndex(matrix, 0, matrix[0].length - 1, target, yIndex);
        if (xIndex == -1) {
            return false;
        }
        return true;
    }

    private int searchTargetXIndex(int[][] matrix, int left, int right, int target, int yIndex) {
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        if (matrix[yIndex][mid] == target) {
            return mid;
        } else if (matrix[yIndex][mid] < target) {
            return searchTargetXIndex(matrix, mid + 1, right, target, yIndex);
        } else {
            return searchTargetXIndex(matrix, left, mid - 1, target, yIndex);
        }
    }

    private int searchTargetYIndex(int[][] matrix, int left, int right, int target) {
        if (left > matrix.length || right < 0) {
            return -1;
        }
        int mid = (left + right) / 2;
        if (matrix[mid][0] == target) {
            return mid;
        } else if (right - left <= 1) {
            if (matrix[right][0] <= target) {
                return right;
            }
            return left;
        } if (matrix[mid][0] < target) {
            return searchTargetYIndex(matrix, mid, right, target);
        } else {
            return searchTargetYIndex(matrix, left, mid, target);
        }
    }

    public static void main(String[] args) {
        Question74 question74 = new Question74();
        int [][]arr = {{1,3,5,7},{10,11,16,20},{23,30,34,50}};
        question74.searchMatrix(arr, 30);
    }
}
